<?php

namespace App\Utils\Mqtt;

use Closure;
use Mosquitto\Client;
use function Hyperf\Support\env;

class EmqxClient
{

    /**EMQX主题订阅
     * @param string $topic
     * @param Closure $closure
     * @param string $clientId
     * @return void
     */
    public function subscribe(string $topic, Closure $closure, string $clientId = "subscribe_default_name"): void
    {
        $client = new Client($clientId);
        $client->setCredentials(env('EMQX_USER', 'root'), env('EMQX_PASSWORD', 'root'));
        $client->connect(env('EMQX_IP', '127.0.0.1'));
        $client->subscribe($topic, 0);
        $client->onMessage(function ($message) use ($closure) {
            $closure($message);
        });
        $client->loopForever(); //底层是循环语句 会保证Proncess进程一直处于挂起的状态
    }

    /**EMQX主题推送
     * @param string $topic
     * @param string $message
     * @param string $clientId
     * @param int $qos
     * @param bool $retain
     * @return void
     */
    public function publish(string $topic, string $message, string $clientId = "publish_default_name", int $qos = 1, bool $retain = false): void
    {
        $client = new Client($clientId);
        $client->setCredentials(env('EMQX_USER', 'root'), env('EMQX_PASSWORD', 'root'));
        $client->connect(env('EMQX_IP', '127.0.0.1'));
        $client->publish($topic, $message, $qos, $retain);
        $client->loop();
        $client->disconnect();
    }
}